#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

void SLTPrint(SLTNode* phead)
{
	SLTNode* node = phead;
	while (node)
	{
		printf("%d->", node->a);
		node = node->next;
	}
	printf("NULL\n");
}

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	if (node == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	node->a = x;
	node->next = NULL;
	return node;
}


void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* node = SLTBuyNode(x);
	if (*pphead==NULL)
	{
		*pphead = node;
		return;
	}
	SLTNode* newnode = *pphead;
	while (newnode->next)
	{
		newnode = newnode->next;
	}
	newnode->next = node;
}


void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* node = SLTBuyNode(x);
	node->next = *pphead;
	*pphead = node;
}

void SLTPopBack(SLTNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLTNode* node = *pphead;
	*pphead = node->next;
	free(node);
	node = NULL;
}


void SLTPopFront(SLTNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLTNode* node = *pphead;
	if (node->next == NULL)
	{
		*pphead = NULL;
		free(node);
		node = NULL;
		return;
	}
	while (node->next->next)
	{
		node = node->next;
	}
	free(node->next);
	node->next = NULL;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* node = phead;
	while (node)
	{
		if (node->a == x)
		{
			return node;
		}
		node = node->next;
	}
	return NULL;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead);
	assert(pos);
	assert(*pphead);
	SLTNode* node = *pphead;
	if (pos == *pphead)
	{
		SLTPushBack(pphead, x);
		return;
	}
	while (node->next != pos)
	{
		node = node->next;
	}
	node->next = SLTBuyNode(x);
	node->next->next = pos;
}


void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pos);
	assert(*pphead);
	assert(pphead);
	if (*pphead == pos)
	{
		SLTPopBack(pphead);
		return;
	}
	SLTNode* node = *pphead;
	while (node->next != pos)
	{
		node = node->next;
	}
	node->next = node->next->next;
	free(pos);
	pos = NULL;
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* node = SLTBuyNode(x);
	node->next = pos->next;
	pos->next = node;
}

void SLTEraseAfter(SLTNode* pos)
{
	assert(pos);
	assert(pos->next);
	SLTNode* node = pos->next;
	pos->next = pos->next->next;
	free(node);
	node= NULL;
}

void SListDesTroy(SLTNode** pphead)
{
	assert(*pphead);
	assert(pphead);
	SLTNode* ml = *pphead;
	while (ml)
	{
		SLTNode* node = ml->next;
		free(ml);
		ml = node;
	}
	*pphead = NULL;
}